import React, { useState, useEffect } from 'react';
import {Card, Table, Pagination, Divider, ResponsiveGrid, Button, Box, Form, Input, Select, Icon, Radio, Upload, Loading,Dialog,Message, } from '@alifd/next';
import styles from './index.module.scss';
import {listPage, optionList, publish, downShelf, deleteCourse, detail, update} from '@/api/CourseAPI'
import AddCourse from '../AddCourse/AddCourse'
import UpdateCourse from '../UpdateCourse/UpdateCourse'

const { Cell } = ResponsiveGrid;
const { Option } = Select;
const FormItem = Form.Item;

// 课程类型，0：自考，1：软考
const courseTypesData = [
  {value: "", label:"请选择"},
  {value: "0", label:"自考"},
  {value: "1", label:"软考"}
];
// 课程状态,0:正常，1:停用，2:已发布,3:已下架, 默认为 0
const courseStatesData = [
  {value:'', label:"请选择"},
  {value:'0', label:"正常"},
  {value:'1', label:"停用"},
  {value:'2', label:"已发布"},
  {value:'3', label:"已下架"}
];
const DEFAULT_DATA = {
  courseTypes: courseTypesData,
  courseStates: courseStatesData,
  courseList: [],
  // 查询参数
  QueryParam: {
    page:{
      current: 1,
      size: 10
    },
    query: "",
    state: null,
    type: null,
  },
  total: 0,
};

/**
 * 课程列表组件
 * 日期：2020-06-21
 */
class CourseList extends React.Component{

  constructor(props) {
    super(props);
    this.state = {
        dataSource: DEFAULT_DATA,
        loading: true,
        updateKey: null,
    };

  }
  // 初始化方法
  componentDidMount(){
    this.onOperation();
  };


  // 加载列表动作
  onOperation = () => {
      // 1.1 调用 UserAPI listPage 接口
      listPage(DEFAULT_DATA.QueryParam).then((data)=>{
        if(data){
          const list = data.records;
          // 处理状态、类型
          if(list){
            for (const i in list) {
              const v = list[i]
              // 处理状态
              for(const j in courseStatesData){
                const s = courseStatesData[j]
                let st = '' + v.state;
                if(st == s.value){
                  v.stateV = s.label
                }
              }
              // 处理类型
              for(const z in courseTypesData){
                const t = courseTypesData[z]
                let tv = '' + v.type;
                if(tv == t.value){
                  v.typeV = t.label
                }
              }
            }
          }
          DEFAULT_DATA.total = data.total;
          DEFAULT_DATA.courseList = list;
          this.setState({ 
            DEFAULT_DATA,
            loading: false,
          }) 
        }
      });
  };

  // 动态变更课程 模糊条件
  changeQuery = (e) => {
    DEFAULT_DATA.QueryParam.query = e
  };
  // 动态变更课程 状态
  changeCourseState = (e) => {
    DEFAULT_DATA.QueryParam.state = e
  };
  // 动态变更课程类型
  changeCourseType = (e) => {
    DEFAULT_DATA.QueryParam.type = e
  };
  // 重置
  onReset = (v) => {
    DEFAULT_DATA.QueryParam.type = null
    DEFAULT_DATA.QueryParam.state = null
    DEFAULT_DATA.QueryParam.query = null
    this.state = {
      DEFAULT_DATA,
      queryValue:'',
    };
  };

  // 下架事件
  downShelfButton = (v) => {
    Dialog.confirm({
      title: '是否下架',
      onOk: () => {
        downShelf(v).then((flag)=>{
          if(flag){
            Message.success('下架成功')
            // 刷新列表数据
            this.onOperation();
          }
        })
      },
    })
  };
  // 发布事件
  publishButton = (v) => {
    Dialog.confirm({
      title: '是否发布',
      onOk: () => {
        publish(v).then((flag)=>{
          if(flag){
            Message.success('发布成功')
            // 刷新列表数据
            this.onOperation();
          }
        })
      },
    })
  };
  // 删除
  delButton = (v) => {
    Dialog.confirm({
      title: '是否确定要删除',
      onOk: () => {
        deleteCourse(v).then((flag)=>{
          if(flag){
            Message.success('删除成功')
            // 刷新列表数据
            this.onOperation();
          }
        })
      },
    })
  };
  // 分页查询：
  onPaginationChange = (e) => {
    DEFAULT_DATA.QueryParam.page.current = e 
    this.state = {
      DEFAULT_DATA
    };
    this.onOperation();
  };
  // 点击查询
  onFindCourse = () =>{
    DEFAULT_DATA.QueryParam.page.current = 1
    this.state = {
      DEFAULT_DATA
    };
    this.onOperation();
  };

  handlerOperatorButton = (value, index, model) =>{
    // console.log('操作***********************')
      // 课程状态,0:正常，1:停用，2:已发布,3:已下架, 默认为 0
      if(model.state == 0 || model.state == 3){
        return (
          <div className={styles.opt}>
            <Button type="primary" text  onClick={()=>this.openUpdateCourse(model.id)}>编辑</Button>
            <Button type="primary" text style={{color: 'green'}} onClick={()=> this.publishButton(model.id) }>发布</Button>
            <Button type="primary" text style={{color: 'red'}} onClick={()=> this.delButton(model.id)}>删除</Button>
          </div>
        )
      }else if(model.state == 2){
        return (
          <div className={styles.opt}>
            <Button type="primary" text style={{color: 'black'}} onClick={()=> this.downShelfButton(model.id)}>下架</Button>
          </div>
        )
      }
  };
  // 打开新增页面
  openAddCourse = (e) =>{
    this.AddCourse.onOpen() 
  };
  // 新增组件引用
  onRefAddCourse = (ref) => {
    this.AddCourse = ref
  }
  // 打开修改页面
  openUpdateCourse = (key) =>{
      this.UpdateCourse.onOpen(key) 
  };
  // 修改组件引用
  onRefUpdateCourse = (ref) => {
    this.UpdateCourse = ref
  }
  // 新增或修改 回调刷新列表
  onFreshList = () => {
    this.onOperation();
  }
  render(){
    return (
      <>
        <Card free>
          <Card.Content>
            <Box padding={10}>
              <Form responsive fullWidth labelAlign="top">
                <FormItem  colSpan={2} label="模糊条件">
                  <Input name='queryParam' onChange={this.changeQuery} placeholder="输入课程名称、副标题、代码" hasClear/>
                </FormItem>
                <FormItem colSpan={2} label="课程状态">
                  <Select name='courseState' placeholder="选择状态" dataSource= {this.state.dataSource.courseStates || []} onChange={this.changeCourseState} hasClear/>
                </FormItem>
                <FormItem colSpan={2} label="课程类型">
                  <Select name='courseType' placeholder="选择类型" dataSource= {this.state.dataSource.courseTypes || []} onChange={this.changeCourseType} hasClear/>
                </FormItem>

                <Cell colSpan={3} className={styles.btns}>
                  <Box spacing={8} direction="row" align="flex-end" justify="center" style={{height: '100%',}}>
                    <Button type="primary" onClick={this.onFindCourse}>查询</Button>
                    <Form.Reset onClick={this.onReset} names={['courseState','courseType','queryParam']}>重置</Form.Reset>
                  </Box>
                </Cell>
              </Form>
            </Box>
            <Divider dashed />
            <div className={styles.Main}>
              <Loading visible={this.state.loading}>
                <div className={styles.add}>
                  <AddCourse onRef={this.onRefAddCourse} onFreshList = {this.onFreshList}  />
                  <UpdateCourse onRef={this.onRefUpdateCourse} onFreshList = {this.onFreshList} />
                  <Button type="primary" onClick={this.openAddCourse}>新增课程</Button>
                </div>
                <Table
                  hasBorder={false}
                  className={styles.Table}
                  dataSource={this.state.dataSource.courseList}
                  rowSelection={{
                    columnProps: () => ({
                      lock: 'left',
                    }),
                  }}
                >
                  <Table.Column title="标识" dataIndex="id" key='id' width={100}/>
                  <Table.Column title="名称" dataIndex="name" key='name' width={250}/>
                  <Table.Column title="副标题" dataIndex="subTitle" key='subTitle' width={500}/>
                  <Table.Column title="代码" dataIndex="code" key='code' width={100}/>
                  <Table.Column title="类型" dataIndex="typeV" key='type' width={100}/>
                  <Table.Column title="状态" dataIndex="stateV" key='state' width={100}/>
                  <Table.Column title="创建时间" dataIndex="createTime" key='createTime' width={200}/>
                  <Table.Column title="操作" cell={this.handlerOperatorButton} />
                </Table>
                <Box margin={[15, 0, 0, 0]} direction="row" align="center" justify="space-between">
                  <div className={styles.total}>
                    每页<span>{this.state.dataSource.QueryParam.page.size}</span>条，共<span>{this.state.dataSource.total}</span>条
                  </div>
                  <Pagination pageSize={this.state.dataSource.QueryParam.page.size} total={this.state.dataSource.total} onChange={this.onPaginationChange} />
                </Box>
              </Loading>
            </div>
          </Card.Content>
        </Card>
      </>
    );
  };
}

export default CourseList;